define(window.backboneCommon.getViewDefine("strategy.detail"), function ($,require,Collection,tpl,ViewSpace,ViewCreative,ViewCreativeEdit,ViewTarget) {
    var backboneView= Backbone.View.extend({
        events: {
            "click #btn_select_space": "selectSpace",
            "click #tb_listSpaces .spaces-delete": "deleteSpaces",
            "click #btn_select_creative": "selectCreative",
            "click #tb_listCreative .creative-delete": "deleteCreative",
            "click #tb_listCreative .creative-edit": "editCreative",
            "click #btn_add_creative": "addCreative",
            "click #btn_submitSave": "submitSave"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.campaign=this.model.get("modelCampaign");
            this.modelAttach.spread=this.model.get("modelSpread");
            this.modelAttach.targetPack=this.model.get("modelTargetPack");
            this.listenTo(this.modelAttach.baseData, "bind:DeliveryTimeType", this.bindDeliveryTimeType);
            this.listenTo(this.modelAttach.campaign, "bind:Info", this.bindCampaign);
            this.listenTo(this.modelAttach.spread, "bind:AllList", this.bindSpread);
            this.listenTo(this.modelAttach.targetPack, "bind:AllList", this.bindTargetPack);
            this.listenTo(this.modelAttach.targetPack, "bind:Info", this.bindTargetPackInfo);
            this.listenTo(this.model, "bind:Info", this.bindInfo);
            this.listenTo(this.model, "save:Info", this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(param){
            var campaignId=param[0];
            if(campaignId){
                this.elementModel={};
                this.extObject={};
                this.pageData={campaignId:campaignId,strategyId:param[1], spaceSelect:{},creativeSelect:{}};
                this.pageData.initSpreadId=$.ExtCommon.getQueryStringByHash("spread");
                this.initViewAttach();
                this._initBodyMain();
            }else{
                $.ExtAssist.goUrlHref("#campaign");
            }
        },
        _initBodyMain:function(){
            this.elementModel.form=$("#form_detail");
            this.elementModel.tbSpaces=$("#tb_listSpaces");
            this.elementModel.tbCreative=$("#tb_listCreative");
            this.elementModel.unitPrice=$("#txt_unitPrice");
            this.elementModel.pTargetPackName=$("#panel_targetPackName");
            this.collection.getCampaignInfo(this.pageData.campaignId);
        },
        initViewAttach:function () {
            var self=this;
            self.viewAttach={};
            self.viewAttach.space=new ViewSpace({pElement:"#container_space",campaignId:self.pageData.campaignId,
                submitCallback:function(json){self._changeSpace(json)}
            });
            self.viewAttach.creative=new ViewCreative({pElement:"#container_creative",campaignId:self.pageData.campaignId,
                submitCallback:function(json){self._bindCreativeTable(json)}
            });
            self.viewAttach.creativeEdit=new ViewCreativeEdit({pElement:"#container_creativeEdit",campaignId:self.pageData.campaignId,
                submitCallback:function(json){self._bindCreativeTable(json)}
            });
        },

        bindCampaign:function () {
            var result=this.modelAttach.campaign.get("dataInfo");
            if(result.res.success){
                this.pageData.campaignInfo=result.res.data;
                this.collection.getInfo({id:this.pageData.strategyId,campaignId:this.pageData.campaignId});
                var name=result.res.data.name;
                $(".campaign-name").attr("title",name).text(name);
                $(".go-campaign-info").attr("href",this._getGoCampaignInfoUrl());
                $.ExtAssist.urlParam.setUrl();
            }
        },
        _getGoCampaignInfoUrl:function () {
            return $.ExtCommon.getStringConnect("#campaign/info/{0}?tabs=1",this.pageData.campaignId);
        },

        bindInfo:function () {
            var self=this;
            var result=this.model.get("dataInfo");
            self.pageData.isAdd=result.isAdd;
            $(".page-operate-title").text($.ExtCommon.getStringConnect("{0}策略",self.pageData.isAdd?"新建":"编辑"));
            if(self.pageData.isAdd){
                result.res.data.startTime=this.pageData.campaignInfo.startTime;
                result.res.data.endTime=this.pageData.campaignInfo.endTime;
                result.res.data.timeType=this.pageData.campaignInfo.timeType;
                result.res.data.isLong=this.pageData.campaignInfo.isLong;
                result.res.data.isRange=this.pageData.campaignInfo.isRange;
                if(!$.ExtCommon.isCheckEmpty(self.pageData.initSpreadId)){
                    result.res.data.spread=self.pageData.initSpreadId;
                }
            }
            self.extObject.formValue=self.elementModel.form.ExtFormValue({initValue:result.res.data,
                initCallback:function(dataJson){
                    self.collection.initAfterDetail(self.pageData.campaignId);
                    self.pageData.strategyInfo=dataJson;
                    self._initDateTime(dataJson);

                    self._initTargetSwitchery(dataJson.isTargetPack);
                    self._changeTargetPack(dataJson.targetPack);
                    self._initTarget(dataJson);

                    if(self.pageData.isAdd){
                        $("#panel_isTargetPack,#panel_targetInfo,#panel_dayBudget,#panel_targetPackName").hide();
                    }else{
                        self._changeSpace(dataJson.spaceInfo,false);
                        self._bindCreativeTable(dataJson.creativeInfo);
                        $("#btn_select_space,#btn_select_creative,#btn_add_creative").prop("disabled", true).hide();
                        self._changeDayBudget(!$.ExtCommon.isCheckEmpty(dataJson.dayBudget));
                    }
                    $.ExtNumeric.initAll();
                    self.elementModel.form.ExtParsley();
                }
            });
            if (!result.res.success) {$.ExtNotify.error("该策略数据获取失败：" +result.res.msg)}
        },

        //推广计划
        bindSpread:function () {
            var self=this;
            var res=this.modelAttach.spread.get("dataAllList");
            self.extObject.spread= $("#ddl_spread").ExtSelect2({placeholder: "-请选择-",minimumResultsForSearch: 1,infoExt: {data: res.data,
                initCallback: function () {
                    self.collection.getTargetPackList({campaignId:self.pageData.campaignId});//查询定向包，定向包数据需根据推广计划类型过滤
                    var info=self.extObject.spread.getValueInfo();
                    if(self.pageData.isAdd){
                        self._changeSpread(info);
                    }else{
                        self.extObject.spread.disabled();
                        self._changeSpreadTime(info);
                        self._changeSpread(info,false);
                    }
                },
                changeCallback: function (value, element,info) {
                    self.elementModel.form.ExtParsley().validate(element);
                    self._changeSpread(info);
                    self._changeSpreadTarget(info);
                    self._changeSpreadTime(info);
                }
            }});
        },
        _changeSpread:function (info,isChangeSpace) {
            isChangeSpace=$.ExtCommon.isCheckBoolean(isChangeSpace)?isChangeSpace:true;
            var kpiName="CPC";
            var isEmpty=$.ExtCommon.isCheckEmpty(info);
            if(!isEmpty){
                if(info.isOrdinary){
                    kpiName="CPC";
                    this._changeDayBudget(false)
                }else if(info.isWeChat){
                    kpiName="CPM";
                    this._changeDayBudget(true);
                }
            }
            kpiName==="CPC"
                ?this.elementModel.unitPrice.attr("data-parsley-numrange","[0.1,100]")
                :this.elementModel.unitPrice.removeAttr("data-parsley-numrange");
            this.elementModel.form.ExtParsley().validate(this.elementModel.unitPrice);
            $("#sp_kpi").text(kpiName);
            $("#btn_select_space").prop("disabled", isEmpty);
            if(isChangeSpace){this._changeSpace({})}
        },
        _changeSpreadTarget:function (info) {
            this.extObject.targetPack.removeDisabled();
            var list=$.ExtCommon.getListClone(this.pageData.targetPackData.group[info.objMatterType.toString()]);
            list.unshift(this._addDataTargetPack());
            this.extObject.targetPack.replaceData(list,"-1");
            $("#panel_targetInfo").show();
        },
        _changeDayBudget:function (b) {
            if(b){
                $("#panel_dayBudget").show().find(":text").attr("required","");
            }else{
                $("#panel_dayBudget").hide().find(":text").removeAttr("required");
            }
        },
        _changeSpreadTime:function (info) {
            if(info.isOrdinary){
                this.extObject.deliveryTimeType.cleanDisabledAll();
            }else if(info.isWeChat){
                var infoTime=this.extObject.deliveryTimeType.getValueInfo();
                if(infoTime.isLong){
                    this.extObject.deliveryTimeType.setValue(1);
                }
                this.extObject.deliveryTimeType.disabledAll();
            }
        },


        //时间
        bindDeliveryTimeType:function () {
            var self=this;
            var res=self.modelAttach.baseData.get("dataDeliveryTimeType");
            this.extObject.deliveryTimeType=$("#panel_deliveryTimeType").ExtRadioCheckbox({type: "radio",attrName:"timeType",initIndex:0,data:res.data,
                initCallback:function () {
                    self._changeDeliveryTimeType();
                },
                changeCallback:function () {
                    self._changeDeliveryTimeType();
                }
            });
        },
        _changeDeliveryTimeType:function(){
            var info=this.extObject.deliveryTimeType.getValueInfo();
            $("#panel_dayTime").toggle(info.isLong);
            $("#panel_rangeTime").toggle(info.isRange)
        },
        _initDateTime:function (json) {
            var self=this;
            var startLongTime,startTime,endTime;
            startLongTime=startTime=endTime=$.ExtMoment.initFormat();
            if(json.isLong){
                startLongTime=json.startTime;
            }else if(json.isRange){
                startTime=json.startTime;
                endTime=json.endTime;
            }
            self.extObject.time=$("#txt_day").ExtDatePicker({initValue:startLongTime});
            self.extObject.timeRang=$("#txt_range").ExtDatePicker({type:"range",startValue:startTime,endValue:endTime,direction:"left"});
        },

        //广告位
        selectSpace:function () {
            var spread= this.extObject.spread.getValue();
            if(!$.ExtCommon.isCheckEmpty(spread)) {
                this.viewAttach.space.init(this.pageData.spaceSelect,{spreadId: spread})
            }
        },
        deleteSpaces:function () {
            this._changeSpace({});
        },
        _bindSpaceTable:function (jsonData) {
            var self=this;
            var isEmpty=$.ExtCommon.isCheckEmpty(jsonData);
            if (isEmpty) {
                self.elementModel.tbSpaces.find("tbody tr").remove();
                self.elementModel.tbSpaces.parent().hide();
            } else {
                self.elementModel.tbSpaces.parent().show();
                if (self.extObject.tbSpaces){self.extObject.tbSpaces.destroy()}
                var options={
                    paging: false,
                    serverSide: false,
                    bInfo: false,
                    columns: [
                        {data: "id", class: "w-50"},
                        {data: "name", class: "w-min-100"},
                        {data: "adFormat", class: "w-80"},
                        {data: "media", class: "w-80"},
                        {data: "platform", class: "w-80"},
                        {data: "describe", class: "w-150"},
                        {data: null, class: "w-60 text-center"}
                    ],
                    infoExt: {data: [jsonData]},
                    createdRow: function (row,data) {
                        var elementTd=$("td", row);
                        elementTd.eq(5).html($.ExtCommon.getStringConnect('<div class="ellipsis-txt-title w-150" title="{0}">{0}</div>',[data.describe]));
                        if(self.pageData.isAdd){ elementTd.eq(6).html('<a class="btn-operate spaces-delete" href="javascript:">删除</a>')}
                    },
                    drawCallback: function () {}
                };
                options.columns[6]["visible"]=self.pageData.isAdd;
                self.extObject.tbSpaces = self.elementModel.tbSpaces.ExtDataTable(options);
            }
            self.pageData.spaceSelect=jsonData;
        },
        _changeSpace:function (data,isChangeCreative) {
            isChangeCreative=$.ExtCommon.isCheckBoolean(isChangeCreative)?isChangeCreative:true;
            this._bindSpaceTable(data);
            if(isChangeCreative){this._bindCreativeTable({})}
            var isDisabled=$.ExtCommon.isCheckEmpty(data.id);
            $("#btn_select_creative").prop("disabled", isDisabled);
            $("#btn_add_creative").prop("disabled", isDisabled).toggle(!isDisabled);
        },

        //创意
        selectCreative:function () {
            var spread= this.extObject.spread.getValue();
            var spaceId=this.pageData.spaceSelect.id;
            if(!$.ExtCommon.isCheckEmpty(spread)&& !$.ExtCommon.isCheckEmpty(spaceId)) {
                this.viewAttach.creative.init(this.pageData.creativeSelect,{spreadId: spread,spaceId:spaceId})
            }
        },
        deleteCreative:function () {
            this._bindCreativeTable({});
        },
        _bindCreativeTable:function (jsonData) {
            var self=this;
            var isEmpty=$.ExtCommon.isCheckEmpty(jsonData);
            if (isEmpty) {
                self.elementModel.tbCreative.find("tbody tr").remove();
                self.elementModel.tbCreative.parent().hide();
            } else {
                self.elementModel.tbCreative.parent().show();
                if (self.extObject.tbCreative){self.extObject.tbCreative.destroy()}
                var options={
                    paging: false,
                    serverSide: false,
                    bInfo: false,
                    columns: [
                        {data: "id", class: "w-50"},
                        {data: "name", class: "w-min-100"},
                        {data: null, class: "w-60 text-center"}
                    ],
                    infoExt: {data: [jsonData]},
                    createdRow: function (row,data) {
                        var elementTd=$("td", row);
                        if(self.pageData.isAdd){
                            elementTd.eq(2).html('<a class="btn-operate creative-delete" href="javascript:">删除</a>')
                        }else{
                            elementTd.eq(2).html($.ExtCommon.getStringConnect('<a class="btn-operate creative-edit" href="javascript:" data-id="{0}">编辑</a>',[data.id]))
                        }
                    },
                    drawCallback: function () {}
                };
                self.extObject.tbCreative = self.elementModel.tbCreative.ExtDataTable(options);
            }
            self.pageData.creativeSelect=jsonData;
        },
        _showModalCreativeEdit:function (id) {
            var spreadInfo= this.extObject.spread.getValueInfo();
            var spaceId=this.pageData.spaceSelect.id;
            if(!$.ExtCommon.isCheckEmpty(spreadInfo)&& !$.ExtCommon.isCheckEmpty(spaceId)) {
                this.viewAttach.creativeEdit.init({spreadInfo:spreadInfo,spaceId:spaceId,creativeId:id})
            }
        },
        addCreative:function () {
            this._showModalCreativeEdit()
        },
        editCreative:function (e) {
            var id=$(e.currentTarget).data("id");
            if(!$.ExtCommon.isCheckEmpty(id)){
                this._showModalCreativeEdit(id.toString());
            }
        },

        //定向
        _initTarget:function (dataJson) {
            var self=this;
            self.viewAttach.target=new ViewTarget({pElement:"#container_target",
                selectData:dataJson.targetData,
                isOperate:dataJson.targetPack==="-1",
                checkAreaCallback:function () {
                    var info=self.extObject.spread.getValueInfo();
                    var type="default";
                    if(info.isOrdinary){type="default"}
                    else if(info.isWeChat){type="group"}
                    return type;
                },
                checkCrowdCallback:function(){
                    return self.pageData.campaignInfo.customer
                }
            });
        },
        bindTargetPack:function () {
            var self=this;
            var res=self.modelAttach.targetPack.get("dataAllList");
            self.pageData.targetPackData=res.data;
            var list=[];
            var spreadInfo= this.extObject.spread.getValueInfo();
            if(self.pageData.isAdd){
                list.push(self._addDataTargetPack())
            }else{
                list=$.ExtCommon.getListClone(res.data.group[spreadInfo.objMatterType.toString()]);
                list.unshift(self._addDataTargetPack());
            }
            self.extObject.targetPack= $("#ddl_targetPack").ExtSelect2({placeholder: "-请选择-",infoExt: {data: list,
                initCallback: function () {
                    if(self.pageData.isAdd){
                        $.ExtCommon.isCheckEmpty(spreadInfo)? self.extObject.targetPack.disabled(): self._changeSpreadTarget(spreadInfo);
                    }
                },
                changeCallback: function (value) {
                    self._changeTargetPack(value);
                    if(value==="-1"){
                        self.viewAttach.target.init({selectData:{},isOperate:true});
                    }else{
                        self.collection.getTargetPackInfo(value)
                    }
                }
            }});
        },
        _addDataTargetPack:function () {
            return {id:"-1",name:"【新建定向包】"};
        },
        _changeTargetPack:function (targetPack) {
            var isAdd=targetPack==="-1";
            if(isAdd && this.extObject.targetPackSwitchery.getValue()){this.extObject.targetPackSwitchery.click(false)}
            $("#panel_isTargetPack").toggle(isAdd);
            isAdd
                ?this.elementModel.pTargetPackName.show().find(":text").attr("required","")
                :this.elementModel.pTargetPackName.hide().find(":text").removeAttr("required");

        },
        _initTargetSwitchery:function (checked) {
            var self=this;
            self.extObject.targetPackSwitchery=$("#cb_targetPack").prop("checked",checked).ExtSwitchery();
        },
        bindTargetPackInfo:function () {
            var result=this.modelAttach.targetPack.get("dataInfo");
            this.viewAttach.target.init({selectData:result.res.data.targetData,isOperate:false});
        },


        _checkForm:function(json){
            $.ExtNotify.destroy();
            var isExtCheck=true;
            var spreadInfo=this.extObject.spread.getValueInfo();
            if(!$.ExtCommon.isCheckEmpty(spreadInfo)){
                if(spreadInfo.isWeChat && $.ExtCommon.isCheckEmpty(json.targetData.area)){
                    isExtCheck=false;
                    $.ExtNotify.error("该推广计划必须包含地域定向");
                }
            }
            if($.ExtCommon.isCheckEmpty(json.creative)){
                isExtCheck=false;
                $.ExtNotify.error("请选择创意");
            }
            if($.ExtCommon.isCheckEmpty(json.space)){
                isExtCheck=false;
                $.ExtNotify.error("请选择广告位");
            }
            return this.elementModel.form.ExtParsley("validate") && isExtCheck;
        },
        submitSave:function () {
            var ajaxData = this.elementModel.form.ExtFormValue("getValues");
            ajaxData.campaignId=this.pageData.campaignId;
            ajaxData.space=this.pageData.spaceSelect.id;
            ajaxData.creative=this.pageData.creativeSelect.id;
            ajaxData.targetData=this.viewAttach.target.getValue();
            if(this._checkForm(ajaxData)) {
                var timeTypeInfo=this.extObject.deliveryTimeType.getValueInfo();
                if(timeTypeInfo.isLong){
                    ajaxData.startTime=this.extObject.time.getValue();
                }else if(timeTypeInfo.isRange){
                    var timeRangeValue=this.extObject.timeRang.getValue();
                    ajaxData.startTime=timeRangeValue[0];
                    ajaxData.endTime=timeRangeValue[1];
                }
                ajaxData.timeTypeInfo=timeTypeInfo;
                ajaxData.spreadInfo=this.extObject.spread.getValueInfo();
                ajaxData.isTargetPack=this.extObject.targetPackSwitchery.getValue();
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                if (infoOriginal.id) {ajaxData.id = infoOriginal.id}
                this.collection.saveInfo(ajaxData);
            }
        },
        saveInfoCallback:function () {
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                $.ExtAssist.goUrlHref(this._getGoCampaignInfoUrl());
            }else{
                $.ExtNotify.error(result.res.msg);
            }
        }

    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el: "#container_body",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function (param) {
            this.view.initMain(param);
        }
    };
    return viewModel;
});